package util;

import java.util.List;

import javax.persistence.Query;

import play.db.jpa.JPA;

public class DAO {
	public static <T> void save(T s) {
		JPA.em().persist(s);
	}

	@SuppressWarnings("unchecked")
	public static <T> List<T> query(Class<T> clazz, String field, Object value) {
		String s = String.format("SELECT x FROM %s x WHERE x.%s = :value",
				clazz.getSimpleName(), field);
		Query q = JPA.em().createQuery(s);
		q.setParameter("value", value);
		return q.getResultList();
	}

	public static <T> T find(Class<T> c, Long id) {
		return JPA.em().find(c, id);
	}

	public static <T> Object navigate(Class<T> clazz, Long id,
			String nameOfAttribute) {
		String s = String.format("SELECT x.%s FROM %s x WHERE x.id = :id",
				nameOfAttribute, clazz.getSimpleName());
		Query q = JPA.em().createQuery(s);
		q.setParameter("id", id);
		return q.getResultList();
	}

	public static <T> void persist(T o) {
		JPA.em().persist(o);
	}

}
